package com.baijiaoxi.common.model.base.service.extension;

import com.baijiaoxi.common.model.base.CommonError;
import com.baijiaoxi.common.model.base.CoreException;
import com.baijiaoxi.common.utils.jdk.BaseTypeParser;

import java.lang.reflect.Field;

/**
 * 允许通过属性名称访问属性
 */
public class FieldSetByNameUtil {
    public static void setFieldValue(Object entity, String fieldName, Object value) {
        setFieldValue(entity, entity.getClass(), fieldName, value);
    }


    private static void setFieldValue(Object entity, Class clazz, String fieldName, Object value) {
        if (fieldName == null || fieldName.isEmpty())
            return;
        if (value == null)
            return;
        if (clazz.getName().equals("java.lang.Object"))
            throw CoreException.create(CommonError.noSuchField, entity, fieldName, value);
        Field field = null;
        try {
            field = clazz.getDeclaredField(fieldName);
        } catch (Exception e) {
            setFieldValue(entity, clazz.getSuperclass(), fieldName, value);
            return;
        }
        field.setAccessible(true);
        Class fieldType = field.getType();
        try {
            switch (fieldType.getName()) {
                case "java.lang.Long" -> field.set(entity, BaseTypeParser.parseToLong(value));
                case "java.lang.String" -> field.set(entity, BaseTypeParser.parseToString(value));
                case "java.lang.Integer" -> field.set(entity, BaseTypeParser.parseToInteger(value));
                case "java.util.Date" -> field.set(entity, BaseTypeParser.parseToDate(value));
                default -> field.set(entity, value);
            }
        } catch (Exception e) {
            throw CoreException.create(CommonError.setFieldValueByNameError, e, fieldName, value);
        }
    }
}
